package mlp.game.cherries;

import java.util.ArrayList;

import com.google.ads.AdView;
import com.overkill.game.GameEngine;
import com.overkill.game.GameOptions;
import com.overkill.game.RenderView;
import com.overkill.game.TheGameActivity;
import com.playtomic.android.api.PlaytomicLeaderboards;
import com.playtomic.android.api.PlaytomicRequestListener;
import com.playtomic.android.api.PlaytomicResponse;
import com.playtomic.android.api.PlaytomicScore;
import com.playtomic.android.api.PlaytomicScoreBoardView;

import mlp.game.cherries.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity extends TheGameActivity {
	public static final String SETTINGS = "mpl.cherryfarm";
	
	int score = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GameOptions options = new GameOptions();	
		gameEngine = new CherryEngine(options, this, 30);		
		
		inizialize(gameEngine, R.id.gameView);
		
		Log.i("SCALE", "is " + GameEngine.DEVICE_DENSITY);
		
		if(GameEngine.DEVICE_DENSITY < DisplayMetrics.DENSITY_TV)
			((AdView)findViewById(R.id.adView)).setVisibility(View.GONE);
		else
			((AdView)findViewById(R.id.adView)).setVisibility(View.VISIBLE);
			
		

		Typeface celestia = Typeface.createFromAsset(getAssets(), RenderView.TYPEFACE_PATH);
		Tools.setTypeFace(this, celestia, R.id.btnSubmit, R.id.btnReplay, R.id.btnQuit, R.id.textScore, R.id.textView1);
    }
    
    @Override
	public void onBackPressed() {
    	if (gameEngine.gameRunning) {
			gameEngine.pauseGame();
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle(R.string.quit_dialog_title)
					.setMessage(R.string.quit_dialog_message)
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									finish();
								}
							}).setNegativeButton(android.R.string.no, null)
					.show();
		} else {
			super.onBackPressed();
		}
	}
       
	@Override
	public void gameOver(GameOptions options) {
		score = options.getInteger("SCORE_GAME_TIME", 0);
		final int speed = options.getInteger("SCORE_SPEED_PERCENT", 0);	
		runOnUiThread(new Runnable() {			
			@Override
			public void run() {
				((AdView)findViewById(R.id.adView)).setVisibility(View.GONE);
				final RelativeLayout scoreLayout = (RelativeLayout)findViewById(R.id.gameoverLayout);
				((TextView)findViewById(R.id.textScore)).setText(getString(R.string.final_score, score, speed));
				AlphaAnimation a = new AlphaAnimation(0f, 1f);
				a.setDuration(200);
				scoreLayout.startAnimation(a);
				scoreLayout.setVisibility(View.VISIBLE);	
			}
		});
	}
	
	public void onButtonClick(View view){
		switch (view.getId()) {
		case R.id.btnQuit:
			finish();
			break;
		case R.id.btnReplay:
			this.restart();
			break;
		case R.id.btnSubmit:
			requestScoreSubmit(score);
			break;
		default:
			break;
		}
	}
	
	public void restart(){
	((RelativeLayout)findViewById(R.id.gameoverLayout)).setVisibility(View.GONE);
		if(GameEngine.DEVICE_DENSITY >= DisplayMetrics.DENSITY_TV)
			((AdView)findViewById(R.id.adView)).setVisibility(View.VISIBLE);
		gameEngine.restart();		
	}
	
	
	@Override
	protected void onDestroy() {
		setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
		super.onDestroy();
	}
	
	private void requestScoreSubmit(final int points){
		final SharedPreferences sharedPreferences = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
		if(sharedPreferences.getBoolean("submit_score", true) == false)
			return;
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(GameActivity.this);
		final EditText editText = new EditText(this);
		editText.setHint("Enter your name");
		editText.setText(sharedPreferences.getString("last_score_name", ""));
		dialog.setCancelable(false);
		dialog.setView(editText);
		dialog.setTitle("Submit score?");
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setMessage("Do you want to submit your score of " + points + " points?");
		dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String name = editText.getText().toString();
				if(name.length() <= 0){
					Toast.makeText(GameActivity.this, "Please enter a name", Toast.LENGTH_SHORT).show();
					requestScoreSubmit(points);
				} else {
					PlaytomicScore score = new PlaytomicScore(name, points);
					leaderBoardSaveAndList(score);
					Editor editor = sharedPreferences.edit();
					editor.putString("last_score_name", name);
					editor.commit();
					dialog.dismiss();
				}								
			}
		});
		dialog.setNegativeButton(android.R.string.no, null);
		dialog.show();
	}
	
	private void leaderBoardSaveAndList(PlaytomicScore score) {
		PlaytomicLeaderboards leaderboards = new PlaytomicLeaderboards();

	    leaderboards.setRequestListener(new PlaytomicRequestListener<PlaytomicScore>() {
	        public void onRequestFinished(PlaytomicResponse<PlaytomicScore> playtomicResponse) {
	            if(playtomicResponse.getSuccess()) {
					Toast.makeText(GameActivity.this, "Your score was submited", Toast.LENGTH_SHORT).show();
	                requestLeaderBoardListFinished(playtomicResponse.getData());
	            }            
	            else {
	                requestLeaderBoardListFailed(playtomicResponse.getErrorCode(), 
	                                                playtomicResponse.getErrorMessage());
	            }
	        }
	    });    
	    
	    leaderboards.saveAndList("High scores", score, true, false, "alltime", 10, null, true, null);
	}

	private void requestLeaderBoardListFinished(final ArrayList<PlaytomicScore> data) {
	   	runOnUiThread(new Runnable() {			
			@Override
			public void run() {
				((Button)findViewById(R.id.btnSubmit)).setEnabled(false);
				((PlaytomicScoreBoardView)findViewById(R.id.listScore)).setData(data);
			}
		});
	}

	private void requestLeaderBoardListFailed(int errorCode, String message) {
		Toast.makeText(this, "Error submitting score\nError: " + message + " (" + errorCode + ")", Toast.LENGTH_LONG).show();
		((Button)findViewById(R.id.btnSubmit)).setEnabled(false);
		Log.i("Leaderboard", "Leaderboard list failed to list because of errorcode #" + errorCode 
	            +  " - Message:" + message);
	}
}

interface GameOverListener {
	public void gameOver(long score, int speed);
}